<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>闭包</title>
  </head>

  <body>
    <script type="text/javascript">
      //内部函数保存在外部，必定闭包
      //导致原有作用链不释放，造成内存泄露（内存减少）
      function test1() {
        var arr = [];
        for (var i = 0; i < 10; i++) {
          arr[i] = function () {
            console.log(i);
          };
        }
        return arr;
      }
      var myArr = test1();
      for (var j = 0; j < 10; j++) {
        myArr[j]();
      }
      //10个10

      function test2() {
        var arr = [];
        for (var i = 0; i < 10; i++) {
          //通过立即执行函数新增立即执行函数的AO 存储j的值
          (function (j) {
            arr[j] = function () {
              console.log(j);
            };
          })(i);
        }
        return arr;
      }
      var myArr = test2();
      for (var j = 0; j < 10; j++) {
        myArr[j]();
      } //0-9

      // 不依赖外部变量
      //  1.实现累加器
      function test3() {
        var num = 0;
        function a() {
          console.log(++num);
          console.log("执行了" + num);
        }
        return a;
      }
      var demo1 = test3();
      demo1();
      //2.用作缓存
      function test4() {
        var food = "apple";
        var obj = {
          eatFood: function () {
            if (food != "") {
              console.log("I am eating " + food);
              food = "";
            } else {
              console.log("there is nothing");
            }
          },
          pushFood: function (myFood) {
            food = myFood;
          },
        };
        return obj;
      }
      var person = test4();
      person.eatFood();
      person.eatFood();
      person.pushFood("banana");
      person.eatFood();

      //变量私有化

      function Person() {
        var name = "黄越";
        this.showName = function () {
          console.log(name);
        };
      }
      //name私有化
      //person.name == undefined
      //只有通过person.showName()才能看到
      var person = new Person();
    </script>
  </body>
</html>
